package models

import (
	"fmt"
	"strings"
	"time"
)

type Model struct {
	Id        int       `gorm:"column:id;primaryKey;autoIncrement" json:"id" form:"id"`
	CreatedAt time.Time `gorm:"column:created_at;autoUpdateTime" json:"created_at" form:"created_at" time_format:"2006-01-02 15:04:05"`
	UpdatedAt time.Time `gorm:"column:updated_at;autoCreateTime" json:"updated_at" form:"updated_at" time_format:"2006-01-02 15:04:05"`
}

type Query struct {
	Field    string `form:"field"`
	Value    any    `form:"value"`
	Operator string `form:"operator"`
	Raw      string `form:"raw"`
}

func GetWhere(query []Query) (string, []any) {
	var bind []any
	if len(query) == 0 {
		return "", bind
	}
	var conditions []string
	pIndex := 1
	for _, q := range query {
		if len(q.Raw) > 0 {
			conditions = append(conditions, q.Raw)
		} else {
			conditions = append(conditions, fmt.Sprintf("%s = :%d", q.Field, pIndex))
			bind = append(bind, q.Value)
			pIndex++
		}
	}
	return fmt.Sprintf(" WHERE %s", strings.Join(conditions, " AND ")), bind
}
